// axios基础的封装
import axios from 'axios'
import { ElMessage } from 'element-plus'
import {userStore} from "@/stores/user.js";
import {categoryStore} from "@/stores/category.js";
import router from "@/router/index.js";
const httpInstance = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// 拦截器

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  const store = userStore();
  //pinia不需要.value,所以这里直接.token
  const token=store.user.token
  if (token) {
    config.headers.Authorization=`Bearer ${token}`
  }
  return config;
}, e => Promise.reject(e))

// axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
  // 统一错误提示
  ElMessage({
    type: 'warning',
    message: e.response.data.message
  })
  //401 token失效处理
  if (e.response.status === 401) {
    const store = userStore();
    store.clearUserInfo();
    // 2.跳转到登录页
    router.push('/login')
  }
  return Promise.reject(e);
})


export default httpInstance